package com.ferris.redbook.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {

    public static class ImageSize {
        private int width;
        private int height;

        public ImageSize(int width, int height) {
            this.width = width;
            this.height = height;
        }

        // getters
    }

    /**
     * 获取图片尺寸
     */
    public static ImageSize getImageSize(InputStream inputStream) throws IOException {
        BufferedImage image = ImageIO.read(inputStream);
        if (image != null) {
            return new ImageSize(image.getWidth(), image.getHeight());
        }
        throw new IOException("无法读取图片尺寸");
    }

    /**
     * 生成缩略图
     */
    public static byte[] generateThumbnail(InputStream inputStream, int maxWidth, int maxHeight) throws IOException {
        BufferedImage originalImage = ImageIO.read(inputStream);
        if (originalImage == null) {
            throw new IOException("无法读取原始图片");
        }

        // 计算缩略图尺寸
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        float ratio = Math.min((float) maxWidth / originalWidth, (float) maxHeight / originalHeight);
        int scaledWidth = (int) (originalWidth * ratio);
        int scaledHeight = (int) (originalHeight * ratio);

        // 创建缩略图
        BufferedImage thumbnail = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = thumbnail.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        g.dispose();

        // 转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(thumbnail, "JPEG", baos);
        return baos.toByteArray();
    }

    /**
     * 压缩图片
     */
    public static byte[] compressImage(InputStream inputStream, float quality) throws IOException {
        // 实现图片压缩逻辑
        // 可以使用 ImageIO 或第三方库如 Thumbnailator
        return null; // 简化实现
    }
}